import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getAllUsers, updateUser } from '@/api/admin'
import { ElMessage } from 'element-plus'

export const useUsersStore = defineStore('users', () => {
  // 状态
  const users = ref([])
  const total = ref(0)
  const pageNum = ref(1)
  const pageSize = ref(10)
  const loading = ref(false)
  const searchText = ref('')
  const dateRange = ref([])
  const sortType = ref('asc')
  const status = ref('all')
  const identity = ref('all')
  const region = ref('all')
  const affiliation = ref('all')
  const ethnicity = ref('all')
  const gender = ref('all')
  // 获取用户列表
  const fetchUsers = async () => {
    loading.value = true
    try {
      const params = {
        pageNum: pageNum.value,
        pageSize: pageSize.value,
        searchText: searchText.value,
        startDate: dateRange.value[0],
        endDate: dateRange.value[1],
        sortType: sortType.value,
        status: status.value,
        identity: identity.value,
        region: region.value,
        affiliation: affiliation.value,
        ethnicity: ethnicity.value,
        gender: gender.value,
      }

      const res = await getAllUsers(params)
      if (res.code === 200) {
        users.value = res.data.items
        total.value = res.data.total
      } else {
        ElMessage.error(res.msg || '获取用户列表失败')
      }
    } catch (error) {
      console.error('获取用户列表失败:', error)
      ElMessage.error('获取用户列表失败')
    } finally {
      loading.value = false
    }
  }

  // 重置筛选条件
  const resetFilters = () => {
    searchText.value = ''
    dateRange.value = []
    sortType.value = 'asc'
    status.value = 'all'
    identity.value = 'all'
    region.value = 'all'
    affiliation.value = 'all'
    ethnicity.value = 'all'
    gender.value = 'all'
    pageNum.value = 1
  }

  return {
    users,
    total,
    pageNum,
    pageSize,
    loading,
    searchText,
    dateRange,
    sortType,
    status,
    identity,
    region,
    affiliation,
    ethnicity,
    gender,
    fetchUsers,
    resetFilters
  }
})
